package com.tanhua.server.server;


import com.tanhua.dubbo.api.*;
import com.tanhua.model.domian.Question;
import com.tanhua.model.domian.Settings;
import com.tanhua.model.domian.User;
import com.tanhua.model.domian.UserInfo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.SettingsVo;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class SettingsService {

    @DubboReference
    private QuestionApi questionApi;
    @DubboReference
    private SettingsApi settingsApi;
    @DubboReference
    private BlackListApi blackListApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @DubboReference
    private UserApi userApi;

    public void savequestions(String content) {
        //获得当前ID
        Long userId = UserHolder.getUserId();
        //调用Api查询question里面的问题
        Question byUserId = questionApi.findByUserId(userId);
        if (byUserId == null) {
            //如果不存在则保存
            Question question = new Question();
            question.setTxt(content);
            question.setUserId(userId);
            questionApi.save(question);
        }else {
            //存在则修改
            byUserId.setTxt(content);
            questionApi.updete(byUserId);
        }
    }

    public SettingsVo settings() {
        SettingsVo settingsVo = new SettingsVo();
        //获取账号ID
        Long id = UserHolder.getUserId();
        settingsVo.setId(id);
        //获取用户手机号
        settingsVo.setPhone(UserHolder.getMobile());
        //获取用户陌生人问题
        Question question = questionApi.findByUserId(id);
        String txt = question == null ? "你喜欢java吗？":question.getTxt();
        settingsVo.setStrangerQuestion(txt);
        //获取用户APP开关设置
        Settings settings = settingsApi.findByUserId(id);
        if (settings != null) {
            settingsVo.setGonggaoNotification(settings.getGonggaoNotification());
            settingsVo.setPinglunNotification(settings.getPinglunNotification());
            settingsVo.setLikeNotification(settings.getLikeNotification());
        }
        return settingsVo;
    }

    public void setting(Map map) {
        //取出前端传来的通用设置数据
        boolean likeNotification = (boolean) map.get("likeNotification");
        boolean pinglunNotification = (boolean) map.get("pinglunNotification");
        boolean gonggaoNotification = (boolean) map.get("gonggaoNotification");

        //获取账户ID
        Long userId = UserHolder.getUserId();

        //从数据库取出本账号通用设置
        Settings settings = settingsApi.findByUserId(userId);
        if (settings == null){
            //如果数据库没有本账号设置，建立一条数据
            Settings settings1 = new Settings();
            settings1.setLikeNotification(likeNotification);
            settings1.setPinglunNotification(pinglunNotification);
            settings1.setGonggaoNotification(gonggaoNotification);
            settings1.setUserId(userId);
            settingsApi.save(settings1);
        }else {
            //如果有本账号设置，则修改本账号设置
            settings.setLikeNotification(likeNotification);
            settings.setPinglunNotification(pinglunNotification);
            settings.setGonggaoNotification(gonggaoNotification);
            settingsApi.updete(settings);
        }
    }

    public PageResult blacklist(int page, int size) {
        //获取用户ID
        Long userId = UserHolder.getUserId();
        /*IPage<UserInfo> iPage = blackListApi.findByUserId(userId, page, size);
        Long total = iPage.getTotal();
        String s= total.toString();
        Integer integer = Integer.valueOf(s);
        PageResult pageResult = new PageResult(page,size, integer,iPage.getRecords());*/
        //获取该账户黑名单总数
        Integer count = userInfoApi.count(userId);
        //获取账户黑名单分页查询的列表数
        List<UserInfo> list = userInfoApi.findblackList(page,size,userId);
        PageResult pageResult = new PageResult(page, size, count, list);
        return pageResult;
    }


    public void blacklistdelete(Long uid) {
        //获取用户ID
        Long userId = UserHolder.getUserId();
       /* //查询被拉黑用户
        LambdaQueryWrapper<BlackList> bqw = new LambdaQueryWrapper<>();
        bqw.eq(BlackList::getUserId,userId).eq(BlackList::getBlackUserId,uid);*/
        blackListApi.blacklistdelete(uid,userId);
    }

    public void sendVerificationCod() {
        String mobile = UserHolder.getMobile();
        //生成随机验证码
        //String s = RandomStringUtils.randomNumeric(6);
        //利用第三方发送短信验证码
        //smsTemplate.sendSms(phone, "123456");
        String s= "123456";
        redisTemplate.opsForValue().set("CHECK_CODE_" + mobile, s, Duration.ofMinutes(5));
        log.info("key={},vliue={}",mobile,s);
    }

    public Map checkVerificationCode(Map map) {
        String verification = (String) map.get("verificationCode");
        String mobile = UserHolder.getMobile();
        //1. 从Redis中获取验证码
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + mobile);
        System.out.println("CHECK_CODE_" + mobile);
        System.out.println(redisCode);
        //2. 校验验证码
        if(StringUtils.isEmpty(verification) || !verification.equals(redisCode)) {
            throw new RuntimeException("验证码校验失败");
        }
        //比对通过 , 删除验证码
        redisTemplate.delete("CHECK_CODE_" + mobile);

        HashMap<String, Boolean> hashMap = new HashMap<String, Boolean>();

        hashMap.put("verification",true);
        return hashMap;
       /* //4. 登录成功, 生成token
        Map<String, Object> tokenMap = new HashMap<String, Object>();
        tokenMap.put("id", UserHolder.getUserId());
        tokenMap.put("mobile", UserHolder.getMobile());
        String token = JwtUtils.getToken(tokenMap);

        //5. 封装数据返回
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("isNew", isNew);

        return result;*/
    }


    public void phone(String phone) {
        User user = new User();
        user.setId(UserHolder.getUserId());
        user.setMobile(phone);
        userApi.update(user);
    }
}
